package com.iot.gateway.aspectj.converter;

import com.iot.gateway.annotation.FieldConverter;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * 字符串转Date
 */
public class MultiFormatDateConverter implements FieldConverter {

    private static final List<DateTimeFormatter> FORMATS = List.of(DateTimeFormatter.ISO_INSTANT, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"), DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm"), DateTimeFormatter.ofPattern("MMM dd, yyyy HH:mm:ss", Locale.ENGLISH));

    @Override
    public Object convert(Object value) {
        if (value instanceof String dateStr) {
            for (DateTimeFormatter fmt : FORMATS) {
                try {
                    return LocalDateTime.parse(dateStr, fmt);
                } catch (DateTimeParseException ignored) {
                }
            }
            throw new IllegalArgumentException("无法解析日期: " + dateStr);
        }
        return ((Date) value).toInstant();
    }

}
